<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-permission="['secKillProduct:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="toAddProduct">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中..." border fit highlight-current-row>
      <el-table-column align="center" label="ID" prop="id" width="80"/>
      <el-table-column align="center" label="产品名称">
        <template slot-scope="scope">
          <el-link type="primary" @click="loadProductTxtAndAttr(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" property="speAttr" label="产品规格"/>
      <el-table-column align="center" property="name" label="秒杀名称"/>
      <el-table-column align="center" property="url" label="产品图片" width="100">
        <template slot-scope="scope">
          <el-image :src="scope.row.url+'_40_40'" @click="loadProductImg(scope.row.id)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" property="price" label="秒杀底价" width="80"/>
      <el-table-column align="center" property="total" label="已售/总数/限购" width="100">
        <template slot-scope="scope">
          {{ scope.row.sales }} / {{ scope.row.total }} / {{ scope.row.limits }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动时间" width="150">
        <template slot-scope="scope">
          {{ scope.row.startTime }}<br>至<br>{{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动进度" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status===100?'':(scope.row.status===200?'success':'info')" effect="plain">{{ scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" prop="seq" width="80"/>
      <el-table-column align="center" label="是否启用" prop="enabled" width="80">
        <template slot-scope="scope">
          <el-switch v-permission="['secKillProduct:enable']" v-model="scope.row.enabled" active-color="#13ce66" inactive-color="#dcdfe6" @change="changeEnabled(scope.row.id,$event)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['secKillProduct:detail']" type="primary" size="mini" @click="detailProductSecKill(scope.row)">编辑</el-button>
          <el-button v-permission="['secKillProduct:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="initList"/>

    <el-drawer :visible.sync="productTxtDialogVisible" :append-to-body="true" :title="productTxt.title" size="50%">
      <el-tabs :stretch="true" v-model="activeTab" type="card">
        <el-tab-pane label="产品属性" name="productAttrTab">
          <el-table :data="productAttrs" :stripe="true" border>
            <el-table-column prop="name" label="名称" align="center"/>
            <el-table-column prop="data" label="值" align="center"/>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="产品详情" name="productTxtTab">
          <div style="text-align:center" v-html="productTxt.content"/>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <el-image-viewer v-if="productImgVisible" :on-close="closeImageViewer" :url-list="productImgs" />

    <el-dialog :close-on-click-modal="false" :title="isAdd?'新增秒杀产品':'编辑秒杀产品'" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="center" label-width="100px">
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item label="产品" prop="productId" style="float:left;width:400px">
          <el-select v-if="isAdd" v-model="dataForm.productId" placeholder="请选择产品" @change="chooseProduct">
            <el-option v-for="(key, index) in products" :key="index" :label="key.name" :value="key.id" />
          </el-select>
          <el-input v-else :value="dataForm.productName" disabled/>
        </el-form-item>
        <el-form-item label="产品规格" prop="sn" style="float:left;width:400px">
          <el-select v-if="isAdd" v-model="dataForm.sn" placeholder="请选择产品规格">
            <el-option v-for="(key, index) in skus" :key="index" :label="key.title +'  剩余:'+ key.stock" :value="key.sn" />
          </el-select>
          <el-input v-else :value="dataForm.speAttr" disabled/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="图片" prop="logo">
          <uploader :file-list.sync="fileList" @success="uploadImgSuccess" @remove="removeImgSuccess"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="活动时间" prop="activityTime" style="float:left;">
          <el-date-picker v-model="dataForm.activityTime" :picker-options="pickerOptions" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" @change="chooseTime"/>
        </el-form-item>
        <el-form-item label="启用状态" prop="status" style="float:left;">
          <el-switch v-model="dataForm.enabled" :active-value="true" :inactive-value="false" active-color="#13ce66"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="秒杀名称" prop="name" style="float:left;">
          <el-input v-model="dataForm.name" placeholder="请输入秒杀名称"/>
        </el-form-item>
        <el-form-item label="秒杀底价" prop="price" style="float:left;">
          <el-input v-model="dataForm.price" :precision="2" :min="0.00" :max="2147483647" placeholder="请输入秒杀底价"/>
        </el-form-item>
        <el-form-item label="排序" prop="seq" style="float:left;">
          <el-input v-model.number="dataForm.seq" placeholder="请输入产品排序"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="已售数量" prop="sales" style="float:left;">
          <el-input v-model.number="dataForm.sales" placeholder="请输入已售数量"/>
        </el-form-item>
        <el-form-item label="总数量" prop="total" style="float:left;">
          <el-input v-model.number="dataForm.total" placeholder="请输入总数量"/>
        </el-form-item>
        <el-form-item label="限购数" prop="limits" style="float:left;">
          <el-input v-model.number="dataForm.limits" placeholder="请输入限购数"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="秒杀规则" prop="rules">
          <el-input v-model="dataForm.rules" type="textarea" rows="5" placeholder="请输入秒杀规则"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button v-permission="['secKillProduct:add']" v-if="isAdd" :loading="submitIng" type="primary" @click="addSecKill">确定</el-button>
        <el-button v-permission="['secKillProduct:edit']" v-else :loading="submitIng" type="primary" @click="editSecKill">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ProductService, ProductSecKillService } from '@/api/ProductService'
import Pagination from '@/components/Pagination'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import Notify from '@/utils/notify'
import Uploader from '@/components/Uploader'

export default {
  name: 'SecKillProductList',
  components: { Pagination, ElImageViewer, Uploader },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      list: [], fileList: [], products: [], skus: [], total: 0, isAdd: true, dialogFormVisible: false,
      productTxtDialogVisible: false, productImgVisible: false,
      productTxt: { title: '', content: '' }, productImgs: [], productAttrs: [],
      listLoading: true, activeTab: 'productAttrTab',
      listQuery: { pageNo: 1, pageSize: 20 }, submitIng: false,
      dataForm: { id: 0, productId: undefined, sn: undefined, name: undefined, enabled: true, rules: undefined, limits: 1, sales: 0, total: 0, price: 0, logo: undefined, startTime: undefined, endTime: undefined, activityTime: [] },
      rules: {
        productId: [{ required: true, message: '产品不能为空!', trigger: 'blur' }],
        sn: [{ required: true, message: '产品规格不能为空!', trigger: 'blur' }],
        logo: [{ required: true, message: '产品图片不能为空!', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空!', trigger: 'blur' }],
        price: [{ required: true, message: '底价不能为空!', trigger: 'blur' }],
        seq: [{ required: true, message: '排序不能为空!', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }],
        activityTime: [{ required: true, message: '活动时间不能为空!', trigger: 'blur' }],
        sales: [{ required: true, message: '销售量不能为空!', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }],
        total: [{ required: true, message: '总数量不能为空!', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }],
        limits: [{ required: true, message: '限购量不能为空!', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }],
        rules: [{ required: true, message: '秒杀规则不能为空!', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    initList() {
      this.listLoading = true
      ProductSecKillService.listProductSecKill(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    search() {
      this.listQuery.pageNo = 1
      this.initList()
    },
    loadProductTxtAndAttr(row) {
      ProductService.getProductTxt(row.id).then(result => {
        this.productTxt.title = row.name
        this.productTxt.content = result.remark
        this.productTxtDialogVisible = true
      })
      ProductService.getProductAttr(row.id).then(result => {
        this.productAttrs = result
      })
    },
    loadProductImg(productId) {
      ProductService.getProductImg(productId).then(result => {
        this.productImgs = result
        if (this.productImgs && this.productImgs.length > 0) {
          this.productImgVisible = true
        }
      })
    },
    closeImageViewer() {
      this.productImgVisible = false
      this.productImgs = []
    },
    chooseProduct() {
      this.dataForm.sn = undefined
      ProductService.listProductSku(this.dataForm.productId).then(result => {
        this.skus = result
      })
    },
    chooseTime(times) {
      this.$set(this.dataForm, 'activityTime', [])
      this.dataForm.startTime = times ? times[0] : undefined
      this.dataForm.endTime = times ? times[1] : undefined
      if (times) {
        this.$set(this.dataForm, 'activityTime', [this.dataForm.startTime, this.dataForm.endTime])
      }
    },
    toAddProduct() {
      this.isAdd = true
      this.dialogFormVisible = true
      ProductService.loadAllProductNames().then(result => {
        this.products = result
      })
    },
    editSecKill() {
      const that = this
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          that.submitIng = true
          delete this.dataForm.activityTime
          ProductSecKillService.editProductSecKill(this.dataForm).then(() => {
            Notify.success(this, '编辑成功!')
            this.initList()
            this.closeDialog()
          })
        }
      })
    },
    addSecKill() {
      const that = this
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          that.submitIng = true
          delete this.dataForm.activityTime
          ProductSecKillService.addProductSecKill(this.dataForm).then(() => {
            Notify.success(this, '新增成功!')
            this.initList()
            this.closeDialog()
          })
        }
      })
    },
    detailProductSecKill(row) {
      this.dataForm = Object.assign({}, row)
      this.isAdd = false
      this.dialogFormVisible = true
      if (this.dataForm.logo) {
        this.fileList.push({ url: this.dataForm.url })
      }
      if (this.dataForm.startTime && this.dataForm.endTime) {
        this.$set(this.dataForm, 'activityTime', [this.dataForm.startTime, this.dataForm.endTime])
      }
    },
    handleDelete(row) {
      this.$confirm('您确认要删除该秒杀产品吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        ProductSecKillService.deleteProductSecKill(row.id).then(() => {
          Notify.success(this, '删除成功!')
          this.initList()
        })
      }).catch(() => {
        return false
      })
    },
    chooseCategory(e) {
      const tag = e[e.length - 1]
      this.listQuery.categoryId = tag
    },
    changeEnabled(secKillId, isEnabled) {
      ProductSecKillService.enableProductSecKill(secKillId, isEnabled).then(() => {
        Notify.success(this, '操作成功!')
        this.initList()
      })
    },
    uploadImgSuccess(data) {
      this.dataForm.logo = data.path
    },
    removeImgSuccess() {
      this.dataForm.logo = undefined
    },
    closeDialog() {
      this.submitIng = false
      this.dialogFormVisible = false
      this.$nextTick(() => {
        this.fileList = []
        this.$refs['dataForm'].resetFields()
        this.dataForm = { id: 0, productId: undefined, sn: undefined, name: undefined, enabled: true, rules: undefined, limits: 1, sales: 0, total: 0, price: 0, logo: undefined, startTime: undefined, endTime: undefined, activityTime: [] }
        this.$refs['dataForm'].clearValidate()
      })
    }
  }
}
</script>
<style>
  .el-drawer__body { overflow-x: auto; }
</style>
